import { computed, reactive, watch, watchEffect, toRefs, nextTick,getCurrentInstance } from "vue";
import { transName } from "@gd-accbuild-core/config/utils";
import {
  util_GetRowAttrVal,
  util_OptionChainHack,
  util_GetCurComponentAttrWithInheritedAttr,
} from "@gd-accbuild-ui/gd-ui/utils/index";
import { genSetterListener } from "./useComponentMetaEventListeners";
//import { computed, watch, ref, reactive, inject } from "vue";
/**
 * 嵌入到维度组件里的原子组件属性
 */
export const embeddedAtomicCompProps = {
  metaItem: {
    type: Object,
    required: true,
  },
  metaItemList: {
    type: Array,
  },
  commonAttr: {
    type: Object,
    default: () => ({}),
  },
  itemSubmitConfig: {
    type: Object,
    default: () => ({
      submitStyle: "Manual",
      allowAutoSubmit: false,
    }),
  },
  vmTemplateConfig: {
    type: Object,
  },
  metaDynmicConfig: {
    type: Object,
  },
  //表格专用 开始
  rowIdx: {
    type: [Number, Object],
    default: () => null,
  },
  colIdx: {
    type: [Number, Object],
    default: () => null,
  },
  rowData: {
    type: Object,
    default: () => null,
  },
  tableBodyData: {
    type: Array,
  },
  //表格专用 结束
  //表单专用 开始
  formData: {
    type: Object,
    default: () => null,
  },
  //表单专用 结束
};

/**
 * 根据不同item容器:表单 / 表格,返回对应的绑定值
 */
export default ({
  props,
  emits = () => {},
  compAttrsKeyDefaultValueMapping = {},
  compAttrsInheritedAttrKeys = ["size", "disabled", "readonly"],
}) => {
  const { proxy: vm } = getCurrentInstance();
  //console.log('初始化绑定',props.metaItem.key,props.rowData,props)
  const containerType = computed(() =>
    props.tableBodyData === null && props.rowIdx === null && props.colIdx === null ? "Form" : "Table"
  );
  /**
   * 获取目标元数据key的值
   */
  const getTargetMetaKeyVal = (metaKey) => {
    if (containerType.value === "Form") {
      return props.formData[metaKey];
    } else {
      //return props.flattenTableBodyData[props.rowIdx][props.metaItem.key];
      return props.rowData[metaKey];
    }
  };
  /**
   * 设置目标元数据key的值
   */
  const setTargetMetaKeyVal = (metaKey, val) => {
    if (containerType.value === "Form") {
      props.formData[metaKey] = val;
    } else {
      //return props.flattenTableBodyData[props.rowIdx][props.metaItem.key];
      props.rowData[metaKey] = val;
    }
  };

  /**
   * 根据是否组合组件，转化绑定值
   */
  const getTransValFromGroup = (metaKey) => {
    const metaItem = props.metaItem;
    const metaItemList = props.metaItemList;
    const isNeedGroupTrans =
      metaItem.hasOwnProperty("groupInfo") && !metaItem.groupInfo.isPartial && metaItem.groupInfo.hasOwnProperty("key");
    if (!isNeedGroupTrans) {
      return getTargetMetaKeyVal(metaKey);
    } else {
      const matchedMetaItemList = metaItemList.filter(
        (el) => el.hasOwnProperty("groupInfo") && el.groupInfo.key === metaItem.groupInfo.key
      );
      //因为此函数在 computed 中调用因此 groupKeyValMapping总是实时的
      const _groupKeyValMapping = matchedMetaItemList.map((el) => [el.key, getTargetMetaKeyVal(el.key)]);
      const groupKeyValMapping = Object.fromEntries(_groupKeyValMapping);
      let valTransFunc = (configObj) => {
        return Object.keys(configObj.groupKeyValMapping).map((key) => configObj.groupKeyValMapping.key);
      };
      if (metaItem.groupInfo["valTransFunc"]) {
        valTransFunc = new Function("configObj", metaItem.groupInfo["valTransFunc"]);
      }
      return valTransFunc({
        metaItem: props.metaItem,
        metaItemList: props.metaItemList,
        commonAttr: props.commonAttr,
        formData: props.formData,
        rowIdx: props.rowIdx,
        colIdx: props.colIdx,
        rowData: props.rowData,
        tableBodyData: props.tableBodyData,
        groupKeyValMapping,
      });
    }
  };

  const setTransValFromGroup = (inputVal) => {
    const metaItem = props.metaItem;
    const metaItemList = props.metaItemList;
    const isNeedGroupTrans =
      metaItem.hasOwnProperty("groupInfo") && !metaItem.groupInfo.isPartial && metaItem.groupInfo.hasOwnProperty("key");
    if (!isNeedGroupTrans) {
      setTargetMetaKeyVal(metaItem.key, inputVal);
      return;
    }
    let groupKeyValMapping = {};
    if (Array.isArray(inputVal)) {
      const matchedMetaItemList = metaItemList.filter(
        (el) => el.hasOwnProperty("groupInfo") && el.groupInfo.key === metaItem.groupInfo.key
      );
      //因为此函数在 computed 中调用因此 groupKeyValMapping总是实时的
      const _groupKeyValMapping = matchedMetaItemList.map((el) => [el.key, getTargetMetaKeyVal(el.key)]);
      groupKeyValMapping = Object.fromEntries(_groupKeyValMapping);
    } else {
      groupKeyValMapping = inputVal;
    }
    Object.keys(configObj.groupKeyValMapping).forEach((key) => {
      setTargetMetaKeyVal(key, configObj.groupKeyValMapping[key]);
    });
  };
  
  let hasExecuteImmediate = false;
  const curBindVal = computed({
    get: () => {
      const val = getTransValFromGroup(props.metaItem.key);
      if (!hasExecuteImmediate) {
        hasExecuteImmediate = true;
        genSetterListener({
          metaItemList: props.metaItemList,
          metaItem: props.metaItem,
          props,
          vm,
          executor: "getter",
        })({ val });
      }
      return val;
    },
    set: async (val) => {
      const isContinueSetter = await genSetterListener({
        metaItemList: props.metaItemList,
        metaItem: props.metaItem,
        props,
        vm,
        executor: "setter",
      })({ val });
      isContinueSetter && setTransValFromGroup(val);
    },
  });
  /////设置默认值
  watchEffect(() => {
    if (props.metaItem.default !== undefined && [undefined, null].includes(curBindVal.value)) {
      curBindVal.value = props.metaItem.default
    }
  });
  /*
    const unwatchDefaultVal = watch(
        () => props.metaItem.default,
        (newVal, oldVal) => {
            nextTick(() => { unwatchDefaultVal() })
            if (newVal !== undefined && [undefined, null].includes(curBindVal.value)) {
                curBindVal.value = newVal;
            }

        },
        { immediate: true }
    );
    */
  //设置componentAttr属性
  const compAttrsOrgKeys = Object.keys(compAttrsKeyDefaultValueMapping);
  const compAttrsKebabKeys = compAttrsOrgKeys.map((el) => transName(el, "Camel", "Kebab"));
  const allCompAttrs = computed(() => {
    const retAttrs = {};
    compAttrsOrgKeys.forEach((orgKey, idx) => {
      const isComponentAttrPath = !["options", "default"].includes(orgKey);
      const prefixPathKeys = isComponentAttrPath ? ["componentAttr"] : [];
      //普通属性设置
      if (!compAttrsInheritedAttrKeys.includes(orgKey)) {
        retAttrs[compAttrsKebabKeys[idx]] = util_GetRowAttrVal(
          props.rowData,
          props.rowIdx,
          props.metaItem,
          [...prefixPathKeys, orgKey],
          compAttrsKeyDefaultValueMapping[orgKey]
        );
      }
      //继承属性设置
      else {
        retAttrs[compAttrsKebabKeys[idx]] = util_GetCurComponentAttrWithInheritedAttr(
          props.rowData,
          props.rowIdx,
          props.metaItem,
          [...prefixPathKeys, orgKey],
          compAttrsKeyDefaultValueMapping[orgKey],
          props.commonAttr
        );
      }
    });
    return retAttrs;
  });
  /////
  return {
    curBindVal,
    containerType,
    allCompAttrs,
  };
};
